<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>海水表面温度克里金插值可视化平台</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Leaflet CSS -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/leaflet/1.9.4/leaflet.css" />
    
    <!-- Font Awesome -->
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: #f8f9fa;
        }
        
        #map {
            height: calc(100vh - 56px);
            width: 100%;
        }
        
        .sidebar {
            position: fixed;
            top: 56px;
            right: 0;
            width: 300px;
            height: calc(100vh - 56px);
            background: white;
            box-shadow: -2px 0 5px rgba(0,0,0,0.1);
            z-index: 1000;
            overflow-y: auto;
            transition: transform 0.3s ease;
        }
        
        .sidebar.collapsed {
            transform: translateX(100%);
        }
        
        .sidebar-toggle {
            position: absolute;
            left: -40px;
            top: 20px;
            background: white;
            border: none;
            border-radius: 4px 0 0 4px;
            padding: 10px;
            box-shadow: -2px 0 5px rgba(0,0,0,0.1);
            cursor: pointer;
        }
        
        .legend {
            background: white;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            margin-bottom: 15px;
        }
        
        .color-scale {
            height: 20px;
            width: 100%;
            background: linear-gradient(to right, #0000ff, #00ffff, #00ff00, #ffff00, #ff0000);
            border-radius: 3px;
            margin: 10px 0;
        }
        
        .loading {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 2000;
            display: none;
        }
        
        .spinner-border {
            width: 3rem;
            height: 3rem;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-dark bg-primary">
        <div class="container-fluid">
            <span class="navbar-brand mb-0 h1">
                <i class="fas fa-water"></i> 海水表面温度克里金插值可视化平台
            </span>
        </div>
    </nav>

    <!-- 主地图容器 -->
    <div id="map"></div>

    <!-- 侧边栏 -->
    <div class="sidebar" id="sidebar">
        <button class="sidebar-toggle" onclick="toggleSidebar()">
            <i class="fas fa-chevron-right" id="toggleIcon"></i>
        </button>
        
        <div class="p-3">
            <h5>控制面板</h5>
            
            <!-- 数据上传 -->
            <div class="card mb-3">
                <div class="card-header">
                    <i class="fas fa-upload"></i> 数据上传
                </div>
                <div class="card-body">
                    <input type="file" class="form-control" id="csvFile" accept=".csv">
                    <button class="btn btn-primary mt-2" onclick="uploadData()">
                        <i class="fas fa-upload"></i> 上传并计算
                    </button>
                    <button class="btn btn-secondary mt-2" onclick="useDefaultData()">
                        <i class="fas fa-refresh"></i> 使用默认数据
                    </button>
                </div>
            </div>

            <!-- 温度范围 -->
            <div class="card mb-3">
                <div class="card-header">
                    <i class="fas fa-thermometer-half"></i> 温度范围
                </div>
                <div class="card-body">
                    <div class="mb-2">
                        <small>最小值: <span id="tempMin">--</span>°C</small>
                    </div>
                    <div class="mb-2">
                        <small>最大值: <span id="tempMax">--</span>°C</small>
                    </div>
                    <div class="mb-2">
                        <small>平均值: <span id="tempMean">--</span>°C</small>
                    </div>
                    <div class="mb-2">
                        <small>采样点数: <span id="sampleCount">--</span></small>
                    </div>
                </div>
            </div>

            <!-- 色阶图例 -->
            <div class="card mb-3">
                <div class="card-header">
                    <i class="fas fa-palette"></i> 温度色阶
                </div>
                <div class="card-body">
                    <div class="color-scale"></div>
                    <div class="d-flex justify-content-between">
                        <small>低温</small>
                        <small>中温</small>
                        <small>高温</small>
                    </div>
                </div>
            </div>

            <!-- 导出选项 -->
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-download"></i> 导出结果
                </div>
                <div class="card-body">
                    <button class="btn btn-success w-100 mb-2" onclick="exportGeoJSON()">
                        <i class="fas fa-file-code"></i> 导出 GeoJSON
                    </button>
                    <button class="btn btn-info w-100" onclick="exportPNG()">
                        <i class="fas fa-image"></i> 导出 PNG
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 加载动画 -->
    <div class="loading" id="loading">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    
    <!-- Leaflet JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/leaflet/1.9.4/leaflet.js"></script>

    <script>
        let map;
        let temperatureLayer;
        let samplePointsLayer;
        let currentData = null;

        // 初始化地图
        function initMap() {
            map = L.map('map').setView([30.0, 123.0], 8);
            
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© OpenStreetMap contributors'
            }).addTo(map);
            
            // 加载默认数据
            loadDefaultData();
        }

        // 切换侧边栏
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const icon = document.getElementById('toggleIcon');
            
            sidebar.classList.toggle('collapsed');
            icon.className = sidebar.classList.contains('collapsed') ? 
                'fas fa-chevron-left' : 'fas fa-chevron-right';
        }

        // 显示加载动画
        function showLoading() {
            document.getElementById('loading').style.display = 'block';
        }

        // 隐藏加载动画
        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
        }

        // 更新温度显示
        function updateTemperatureDisplay(data) {
            document.getElementById('tempMin').textContent = data.temperature_range.min.toFixed(1);
            document.getElementById('tempMax').textContent = data.temperature_range.max.toFixed(1);
            document.getElementById('tempMean').textContent = data.temperature_range.mean.toFixed(1);
            document.getElementById('sampleCount').textContent = data.sample_points;
        }

        // 渲染温度热力图
        function renderTemperatureLayer(geojson) {
            if (temperatureLayer) {
                map.removeLayer(temperatureLayer);
            }
            
            const tempFeatures = geojson.features.filter(f => f.geometry.type === 'Polygon');
            
            temperatureLayer = L.geoJSON({
                type: "FeatureCollection",
                features: tempFeatures
            }, {
                style: function(feature) {
                    const temp = feature.properties.temperature;
                    return {
                        fillColor: getTemperatureColor(temp),
                        weight: 0.5,
                        opacity: 0.8,
                        color: 'white',
                        fillOpacity: 0.7
                    };
                }
            }).addTo(map);
        }

        // 渲染采样点
        function renderSamplePoints(geojson) {
            if (samplePointsLayer) {
                map.removeLayer(samplePointsLayer);
            }
            
            const sampleFeatures = geojson.features.filter(f => f.properties.type === 'sample_point');
            
            samplePointsLayer = L.geoJSON({
                type: "FeatureCollection",
                features: sampleFeatures
            }, {
                pointToLayer: function(feature, latlng) {
                    const temp = feature.properties.temperature;
                    
                    return L.circleMarker(latlng, {
                        radius: 8,
                        fillColor: '#ff0000',
                        color: '#fff',
                        weight: 2,
                        opacity: 1,
                        fillOpacity: 0.8
                    }).bindPopup(`温度: ${temp.toFixed(1)}°C`);
                }
            }).addTo(map);
        }

        // 根据温度获取颜色
        function getTemperatureColor(temp) {
            const min = currentData.temperature_range.min;
            const max = currentData.temperature_range.max;
            const ratio = (temp - min) / (max - min);
            
            // 蓝色到红色的渐变
            const r = Math.round(255 * ratio);
            const g = Math.round(255 * (1 - Math.abs(ratio - 0.5) * 2));
            const b = Math.round(255 * (1 - ratio));
            
            return `rgb(${r}, ${g}, ${b})`;
        }

        // 加载默认数据
        function loadDefaultData() {
            showLoading();
            fetch('/api/interpolate', {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                currentData = data;
                updateTemperatureDisplay(data);
                renderTemperatureLayer(data.geojson);
                renderSamplePoints(data.geojson);
                hideLoading();
            })
            .catch(error => {
                console.error('Error:', error);
                hideLoading();
                alert('加载数据失败: ' + error.message);
            });
        }

        // 上传数据
        function uploadData() {
            const fileInput = document.getElementById('csvFile');
            const file = fileInput.files[0];
            
            if (!file) {
                alert('请选择CSV文件');
                return;
            }
            
            const formData = new FormData();
            formData.append('file', file);
            
            showLoading();
            fetch('/api/interpolate', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                currentData = data;
                updateTemperatureDisplay(data);
                renderTemperatureLayer(data.geojson);
                renderSamplePoints(data.geojson);
                hideLoading();
            })
            .catch(error => {
                console.error('Error:', error);
                hideLoading();
                alert('上传失败: ' + error.message);
            });
        }

        // 使用默认数据
        function useDefaultData() {
            loadDefaultData();
        }

        // 导出GeoJSON
        function exportGeoJSON() {
            if (!currentData) {
                alert('请先生成数据');
                return;
            }
            
            fetch('/api/export', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    format: 'geojson',
                    geojson: currentData.geojson
                })
            })
            .then(response => response.blob())
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'sst_interpolation.geojson';
                a.click();
                window.URL.revokeObjectURL(url);
            })
            .catch(error => {
                console.error('Error:', error);
                alert('导出失败: ' + error.message);
            });
        }

        // 导出PNG
        function exportPNG() {
            // 使用html2canvas库实现
            alert('PNG导出功能需要集成html2canvas库，当前版本暂不支持');
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initMap();
        });
    </script>
</body>
</html>